//
//  UserManager.swift
//  mycloudmusicswift
//
//  Created by smile on 2019/4/22.
//  Copyright © 2019 ixuea. All rights reserved.
//

import Foundation

//导入响应式编程框架
import RxSwift

class UserManager {
    
    /// 单例
    private static var instance:UserManager?
    
    //负责对象销毁
    //这个功能类似NotificationCenter的removeObserver
    let disposeBag = DisposeBag()
    
    /// 用来缓存用户列表
    var userCaches:[String:User]=[:]
    
    /// 获取单例
    ///
    /// - Returns: <#return value description#>
    static func shared() -> UserManager {
        if instance==nil {
            instance = UserManager()
        }
        return instance!
    }
    
    /// 根据Id获取用户对象
    ///
    /// - Parameters:
    ///   - id: <#id description#>
    ///   - success: <#success description#>
    func getUser(_ id:String,_ success:@escaping  (_ data:User) -> Void) {
        //先从缓存获取
        let data=userCaches[id]

        if let data = data {
            //如果有user，直接回调
            success(data)
            return
        }

        //没有user
        //请求接口
        Api.shared
            .userDetail(id)
            .subscribeOnSuccess { (data) in
                if  let data = data?.data {
                    //将用户保存到缓存中
                    self.userCaches[id]=data
                    
                    //回调方法
                    success(data)
                }
            }.disposed(by: disposeBag)
        
    }
}
